package com.ybkj.daijia.api.apirest.v4;

import com.alibaba.fastjson.JSONObject;
import com.ybkj.daijia.OrderConfirmLocs;
import com.ybkj.daijia.Setting;
import com.ybkj.daijia.serverUtils.SettingUtils;
import com.ybkj.daijia.api.driver.transport.ResultTransport;
import com.ybkj.daijia.api.util.ErrorConstantV4;
import com.ybkj.daijia.common.Result;
import com.ybkj.daijia.config.ZWYApi;
import com.ybkj.daijia.server.event.model.ActivityCheckEvent;
import com.ybkj.daijia.server.event.model.MemberRebateEvent;
import com.ybkj.daijia.server.event.model.OrderConfirmEvent;
import com.ybkj.daijia.server.event.model.OrderEmployHasPayEvent;
import com.ybkj.daijia.server.event.model.OrderFinishEvent;
import com.ybkj.daijia.server.event.model.OrderPassengerHasPayEvent;
import com.ybkj.daijia.server.mc.Enterprise;
import com.ybkj.daijia.server.mc.Passenger;
import com.ybkj.daijia.server.model.Company;
import com.ybkj.daijia.server.model.Driver;
import com.ybkj.daijia.server.model.FirstOrderPassenger;
import com.ybkj.daijia.server.model.Order;
import com.ybkj.daijia.server.model.Order.PayTypeDetails;
import com.ybkj.daijia.server.model.OrderLocation;
import com.ybkj.daijia.server.model.OrderLocationMany;
import com.ybkj.daijia.server.reactor.ReactorVo;
import com.ybkj.daijia.server.sales.Activity.ActivityEvent;
import com.ybkj.daijia.server.sales.Activity.OrderType;
import com.ybkj.daijia.server.sales.Coupon;
import com.ybkj.daijia.server.sales.CouponRule;
import com.ybkj.daijia.server.service.CompanyService;
import com.ybkj.daijia.server.service.CouponService;
import com.ybkj.daijia.server.service.DriverService;
import com.ybkj.daijia.server.service.FirstOrderPassengerService;
import com.ybkj.daijia.server.service.MemberService;
import com.ybkj.daijia.server.service.OrderLocationManyService;
import com.ybkj.daijia.server.service.OrderService;
import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.ApplicationEventMulticaster;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

@Controller("ApiDaijiaProcessControllerV4")
@RequestMapping(value = "api/daijia/v4/")
public class DaijiaProcessController {

    private static final Logger logger = LoggerFactory.getLogger(DaijiaProcessController.class);

    @Autowired
    private CompanyService companyService;
    @Autowired
    private DriverService driverService;
    @Autowired
    private OrderService orderService;
    @Autowired
    private MemberService memberService;
    @Autowired
    private CouponService couponService;
    @Autowired
    private ApplicationEventMulticaster applicationEventMulticaster;
    @Autowired
    private FirstOrderPassengerService firstOrderPassengerService;
    @Autowired
    private OrderLocationManyService orderLocationManyService;
    @Autowired
    private SettingUtils settingUtils;

    @Autowired
    private ZWYApi zWYApi;

    /**
     * 查询司机提现、推广开关状态（0-不允许  1-允许）
     *
     * @return
     */
    @RequestMapping("checkSwitch")
    @ResponseBody
    public ResultTransport checkSwitch(@RequestParam("driverId") Long driverId) {
        Driver driver = driverService.findOne(driverId);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("tixian", driver.getTixian());
        jsonObject.put("tuiguang", driver.getTuiguang());
        ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
        instance.setData(jsonObject);
        return instance;
    }

    @RequestMapping(value = "completeTaskData", method = RequestMethod.GET)
    public @ResponseBody
    ResultTransport completeTaskData(Long orderId) {

        logger.error("recv orderId:{}", orderId);

        if (null == orderId) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        Order order = orderService.findOne(orderId);

        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }

        if (!order.getStatus().equals(Order.ORDER_STATUS_BUSY)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
        }

        if (null == order.getStartDriveDate()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
        }

        Driver driver = driverService.findOne(order.getDriverId());
        if (null == driver) {
            return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
        }

        Passenger passenger = memberService.findOnePassenger(order.getClientId());
        if (null == passenger) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PASSENGER_NOT_EXISTS);
        }

        try {

            Map<String, Object> map = new HashMap<String, Object>();
            map.put("orderId", order.getId());
            map.put("orderNumber", order.getOrderNumber());
            map.put("orderType", "daijia");

            map.put("passengerPhone", passenger.getPhone());
            map.put("passengerName", passenger.getName());
            map.put("passengerType", passenger.getTypeStr());

            // 等级
            map.put("passengerGrade", passenger.getGrade_name());

            Company orderCompany = companyService.findOne(order.getCompanyId());
            map.put("orderCompanyName", orderCompany.getAbbreviation());

            Company passengerCompany = companyService.findOne(passenger.getCompanyId());
            map.put("passengerCompanyName", passengerCompany.getAbbreviation());

            if (passenger.getType() == Passenger.TYPE_PASSENGER) {
                map.put("overdraw", passenger.isAllowOverdraw());
                map.put("virtual",
                    passenger.getDrawMoney().add(passenger.getNodrawMoney())
                        .setScale(2, BigDecimal.ROUND_HALF_UP));
            } else if (passenger.getType() == Passenger.TYPE_ENTERPRISE) {
                Enterprise enterprise = memberService
                    .findOneEnterprise(passenger.getEnterprise_id());
                map.put("overdraw", enterprise.isAllowOverdraw());
                map.put("virtual",
                    enterprise.getDrawMoney().add(enterprise.getNodrawMoney()).setScale(2,
                        BigDecimal.ROUND_HALF_UP));
            }

            // 优惠券
            if (null != order.getCouponId()) {
                Coupon coupon = couponService.findOne(order.getCouponId());
                if (null != coupon) {
                    CouponRule couponRule = coupon.getCouponRule();
                    if (couponRule.getType().equals(CouponRule.TYPE_DEDUCTION)) {
//                        map.put("couponMoney", couponRule.getMoney());
                        map.put("couponMoney", coupon.getCouponPrice());
                    } else if (couponRule.getType().equals(CouponRule.TYPE_DISCOUNT)) {
//                        map.put("discount", couponRule.getDiscount());
                        map.put("discount", coupon.getCouponDiscount());
                    }
                }
            }

            // 预先支付
            BigDecimal preyMoney = BigDecimal.ZERO;
            if (null != order.getAlipayMoney() && order.getAlipayMoney().doubleValue() > 0) {
                preyMoney = order.getAlipayMoney();
            } else if (null != order.getWeixinMoney() && order.getWeixinMoney().doubleValue() > 0) {
                preyMoney = order.getWeixinMoney();
            } else if (null != order.getUnionpayMoney()
                && order.getUnionpayMoney().doubleValue() > 0) {
                preyMoney = order.getUnionpayMoney();
            } else if (null != order.getBestpayMoney()
                && order.getBestpayMoney().doubleValue() > 0) {
                preyMoney = order.getBestpayMoney();
            } else if (null != order.getSignMoney() && order.getSignMoney().doubleValue() > 0) {
                preyMoney = order.getSignMoney();
            } else if (null != order.getBalanceMoney()
                && order.getBalanceMoney().doubleValue() > 0) {
                preyMoney = order.getBalanceMoney();
            }
            map.put("preyMoney", preyMoney.setScale(2, BigDecimal.ROUND_HALF_UP));

            // 首单免费
            Long completeTimes = firstOrderPassengerService.selectAll(passenger.getId(),
                FirstOrderPassenger.FREE_ORDERTYPE_DAIJIA);
            if (completeTimes > 0) {
                map.put("firstFree", false);
            } else {
                map.put("firstFree", true);
            }

            map.put("employId", driver.getId());
            map.put("employName", driver.getName());
            map.put("employPhone", driver.getPhone());

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
            instance.setData(map);
            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
            instance.setMessage(e.getMessage());
            return instance;
        }

    }

    @RequestMapping(value = "checkTask", method = RequestMethod.GET)
    public @ResponseBody
    ResultTransport checkTask(Long orderId) {

        if (null == orderId) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        Order order = orderService.findOne(orderId);

        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }

        try {

            boolean finished = false;
            if (order.getStatus().equals(Order.ORDER_STATUS_BAODAN)
                || order.getStatus().equals(Order.ORDER_STATUS_FINISHED)) {
                finished = true;
            }

            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
            instance.setData(finished);
            return instance;

        } catch (Exception e) {
            e.printStackTrace();
            return ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
        }

    }

    /**
     * @param orderId
     * @param realCash
     * @param guoluMoney
     * @param yuanchengMoney
     * @param otherMoney
     * @param mileage
     * @param waitedTime
     * @param travelTime
     * @param toPlace
     * @param toPlaceLng
     * @param toPlaceLat
     * @param startPrice
     * @param mileagePrice
     * @param runTimePrice
     * @param waitPrice
     * @param memo
     * @return
     */
    @RequestMapping(value = "confirmTask", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport confirmTask(Long orderId, BigDecimal realCash, BigDecimal guoluMoney,
        BigDecimal yuanchengMoney, BigDecimal otherMoney, Double mileage, Integer waitedTime,
        Integer travelTime,
        @RequestParam(required = false, value = "toPlace") String toPlace,
        @RequestParam(required = false, value = "toPlaceLng") Double toPlaceLng,
        @RequestParam(required = false, value = "toPlaceLat") Double toPlaceLat,
        @RequestParam(required = false, value = "startPrice") BigDecimal startPrice,
        @RequestParam(required = false, value = "mileagePrice") BigDecimal mileagePrice,
        @RequestParam(required = false, value = "runTimePrice") BigDecimal runTimePrice,
        @RequestParam(required = false, value = "waitPrice") BigDecimal waitPrice,
        @RequestParam(required = false, value = "memo") String memo,
        @RequestParam(required = false, value = "jsonLocs") String jsonLocs) {

        // realCash应为app计算出的金额 不包含优惠券
        return confirmTaskFunction(orderId, realCash, guoluMoney, yuanchengMoney, otherMoney,
            mileage, waitedTime,
            travelTime, toPlace, toPlaceLng, toPlaceLat, startPrice, mileagePrice, runTimePrice,
            waitPrice, memo,
            null, null, jsonLocs, null);

    }

    @RequestMapping(value = "confirmTaskJsonFile", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport confirmTaskJsonFile(Long orderId, BigDecimal realCash, BigDecimal guoluMoney,
        BigDecimal yuanchengMoney, BigDecimal otherMoney, Double mileage, Integer waitedTime,
        Integer travelTime,
        @RequestParam(required = false, value = "toPlace") String toPlace,
        @RequestParam(required = false, value = "toPlaceLng") Double toPlaceLng,
        @RequestParam(required = false, value = "toPlaceLat") Double toPlaceLat,
        @RequestParam(required = false, value = "startPrice") BigDecimal startPrice,
        @RequestParam(required = false, value = "mileagePrice") BigDecimal mileagePrice,
        @RequestParam(required = false, value = "runTimePrice") BigDecimal runTimePrice,
        @RequestParam(required = false, value = "waitPrice") BigDecimal waitPrice,
        @RequestParam(required = false, value = "memo") String memo,
        @RequestParam(required = false, value = "justKilometres") Double justKilometres,
        @RequestParam(required = false, value = "justMoney") BigDecimal justMoney,
        @RequestParam(required = false, value = "jsonLocs") String jsonLocs,
        @RequestParam(required = false, value = "jsonLocFile") MultipartFile jsonLocFile) {

        return confirmTaskFunction(orderId, realCash, guoluMoney, yuanchengMoney, otherMoney,
            mileage, waitedTime,
            travelTime, toPlace, toPlaceLng, toPlaceLat, startPrice, mileagePrice, runTimePrice,
            waitPrice, memo,
            justKilometres, justMoney, jsonLocs, jsonLocFile);

    }

    private ResultTransport confirmTaskFunction(Long orderId, BigDecimal realCash,
        BigDecimal guoluMoney,
        BigDecimal yuanchengMoney, BigDecimal otherMoney, Double mileage, Integer waitedTime,
        Integer travelTime,
        String toPlace, Double toPlaceLng, Double toPlaceLat, BigDecimal startPrice,
        BigDecimal mileagePrice,
        BigDecimal runTimePrice, BigDecimal waitPrice, String memo, Double justKilometres,
        BigDecimal justMoney,
        String jsonLocs, MultipartFile jsonLocFile) {

        logger.error(
            "recv orderId:{}," + "realCash:{},guoluMoney:{},yuanchengMoney:{},otherMoney:{},"
                + "mileage:{},waitedTime:{},travelTime:{},"
                + "toPlace:{},toPlaceLng:{},toPlaceLat:{},"
                + "startPrice:{},mileagePrice:{},runTimePrice:{},waitPrice:{}",
            orderId, realCash, guoluMoney, yuanchengMoney, otherMoney, mileage, waitedTime,
            travelTime, toPlace,
            toPlaceLng, toPlaceLat, startPrice, mileagePrice, runTimePrice, waitPrice);

        if (null == orderId || null == realCash || null == mileage || null == waitedTime
            || null == travelTime) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        Order order = orderService.findOne(orderId);

        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }

        if (!order.getStatus().equals(Order.ORDER_STATUS_BUSY)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
        }

        if (null == order.getStartDriveDate()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
        }

        if (order.isTreatment()) {
            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
            instance.setData("waitfinish");
            return instance;
        }

        try {
            BigDecimal hasPayed = BigDecimal.ZERO;// 之前已经实际支付的钱

            hasPayed = hasPayed.add(order.getSignMoney());

            hasPayed = hasPayed.add(order.getBalanceMoney());

            hasPayed = hasPayed.add(order.getAlipayMoney());

            hasPayed = hasPayed.add(order.getWeixinMoney());

            hasPayed = hasPayed.add(order.getUnionpayMoney());

            hasPayed = hasPayed.add(order.getBestpayMoney());

            order.setGuoluMoney(guoluMoney);
            order.setYuanchengMoney(yuanchengMoney);
            order.setOtherMoney(otherMoney);
            order.setRealCash(realCash);
            // 优惠券
            Coupon coupon = null;
            BigDecimal coupon_hasPayed = BigDecimal.ZERO;
            Double discount = null;
            if (null != order.getCouponId()) {
                coupon = couponService.findOne(order.getCouponId());
                if (null != coupon) {
                    if (coupon.getCouponRule().getType().equals(CouponRule.TYPE_DEDUCTION)) {
//                        coupon_hasPayed = coupon.getCouponRule().getMoney();
                        coupon_hasPayed = coupon.getCouponPrice();
                    } else if (coupon.getCouponRule().getType().equals(CouponRule.TYPE_DISCOUNT)) {
//                        discount = coupon.getCouponRule().getDiscount();
                        discount = coupon.getCouponDiscount();
                        coupon_hasPayed = realCash.subtract(order.getGuoluMoney())
                            .multiply(
                                new BigDecimal(1)
                                    .subtract(new BigDecimal(discount).divide(new BigDecimal(10))))
                            .setScale(0, BigDecimal.ROUND_DOWN);
                    }
                }
            }

            order.setCouponMoney(coupon_hasPayed);
            if (coupon_hasPayed.doubleValue() > 0 && null == order.getPrePayTypeDetail()) {
                order.setPrePayTypeDetail(Order.PayTypeDetails.coupon);
            }
            order.setDiscount(discount);

            BigDecimal m = new BigDecimal(mileage);
            double df = m.setScale(1, BigDecimal.ROUND_HALF_UP).doubleValue();
            order.setMileage(df);

            order.setWaitedTime(waitedTime);
            order.setTravelTime(travelTime);

            order.setStartPrice(startPrice);
            order.setMileagePrice(mileagePrice);
            order.setTravelPrice(runTimePrice);
            order.setWaitedPrice(waitPrice);

            if (StringUtils.isNotBlank(toPlace) && null != toPlaceLng && null != toPlaceLat) {
                if (StringUtils.isBlank(order.getToPlace())) {
                    order.setToPlaceLongitude(toPlaceLng);
                    order.setToPlaceLatitude(toPlaceLat);
                    order.setToPlace(toPlace);
                }
            }

            order.setTreatment(true);
            order.setTreatmentDate(new Date());
            if (StringUtils.isNotBlank(memo)) {
                order.setCarNumber(memo);
            }
            if (null != justKilometres) {
                order.setJustKilometres(justKilometres);
            }
            if (null != justMoney) {
                order.setJustMoney(justMoney);
            }

            // 确认并报单
            orderService.reportV3(order, null);

            Passenger passenger = memberService.findOnePassenger(order.getClientId());
            if (StringUtils.isNotBlank(memo)) {
                passenger.setPlateNumber(memo);
                memberService.updatePassenger(passenger);
            }

            // 保存位置
            if (null != jsonLocFile) {
                jsonLocs = OrderConfirmLocs.locs(jsonLocFile);
            }

            if (StringUtils.isNotBlank(jsonLocs)) {
                OrderLocationMany orderLocationMany = new OrderLocationMany();
                orderLocationMany.setOrderId(orderId);
                orderLocationMany.setOrderType(OrderLocation.OrderType.daijia);
                orderLocationMany.setJsonLocs(jsonLocs);
                orderLocationManyService.save(orderLocationMany);
            }

            BigDecimal money = order.getRealCash();// 还需支付的钱
            money = money.subtract(order.getGuoluMoney());
            money = money.subtract(coupon_hasPayed);
            if (money.doubleValue() < 0) {
                money = BigDecimal.ZERO;
            }
            money = money.subtract(hasPayed);
            money = money.add(order.getGuoluMoney());

            Driver driver = driverService.findOne(order.getDriverId());
            orderService.confirmTaskV4(order, driver);
            //0898JHDJ3  全额抵扣
            if (money.doubleValue() <= 0
                || (null != order.getPreferentialType() && order.getPreferentialType()
                .equals("0898JHDJ3"))) {
                // 直接结算
                Result<Order> result = null;
                // 醉无忧 - 人保新加
                if (null != order.getOrderNoRenBao() && null != order.getCuponNoRenBao()) {
                    result = orderService
                        .completeTaskNewV3(order, passenger, driver, "renBaoPay", null, hasPayed,
                            false);
                } else {
                    // 直接结算
                    result = orderService
                        .completeTaskNewV3(order, passenger, driver, "clickComplete", null,
                            hasPayed,
                            false);
                }
                if (result.isSuccess()) {
                    // 完成工单事件
                    ReactorVo rVo = new ReactorVo();
                    rVo.setDriver(driver);
                    rVo.setOrder(order);

                    OrderEmployHasPayEvent orderEmployHasPayEvent = new OrderEmployHasPayEvent(
                        passenger, order.getId(),
                        "daijia");
                    applicationEventMulticaster.multicastEvent(orderEmployHasPayEvent);

                    OrderFinishEvent finishEvent = new OrderFinishEvent(rVo);
                    applicationEventMulticaster.multicastEvent(finishEvent);

                    if (null != passenger) {
                        ReactorVo rVo2 = new ReactorVo();
                        rVo2.setOrderChannelName(order.getOrderType());
                        rVo2.setOrderType(OrderType.daijia);
                        rVo2.setPassenger(passenger);
                        rVo2.setActivityEvent(ActivityEvent.orderCompleteTimes);
                        ActivityCheckEvent activityCheckEvent = new ActivityCheckEvent(rVo2);
                        applicationEventMulticaster.multicastEvent(activityCheckEvent);

                        MemberRebateEvent memberRebateEvent = new MemberRebateEvent(passenger,
                            order,
                            order.getRealCash(), 1);
                        applicationEventMulticaster.multicastEvent(memberRebateEvent);
                    }

                    ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
                    instance.setData("hasfinished");
                    return instance;
                } else {
                    ResultTransport instance = ResultTransport
                        .getErrorBy(ErrorConstantV4.SERVER_ERROR);
                    return instance;
                }
            } else {
                // 进入确认页面
                // 醉无忧 - 人保新加
                if (null != order.getOrderNoRenBao() && null != order.getCuponNoRenBao()) {
                    if (null != order.getOrderNoRenBao() && null != order.getCuponNoRenBao()) {
                        if (null != order.getPreferentialType()) {
                            // 0898JHDJ1 == 38 0898JHDJ2 == 58 抵扣的金额
                            if (order.getPreferentialType().equals("0898JHDJ1")) {
                                realCash = realCash.subtract(new BigDecimal(38));
                            } else if (order.getPreferentialType().equals("0898JHDJ2")) {
                                realCash = realCash.subtract(new BigDecimal(58));
                            }
                        }
                    }
                    if (realCash.doubleValue() < 0) {
                        // 直接结算
                        Result<Order> result = null;
                        // order.setRealCash(BigDecimal.ZERO);
                        result = orderService
                            .completeTaskNewV3(order, passenger, driver, "renBaoPay", null,
                                hasPayed,
                                false);
                        if (result.isSuccess()) {
                            // 完成工单事件
                            ReactorVo rVo = new ReactorVo();
                            rVo.setDriver(driver);
                            rVo.setOrder(order);

                            OrderEmployHasPayEvent orderEmployHasPayEvent = new OrderEmployHasPayEvent(
                                passenger, order.getId(),
                                "daijia");
                            applicationEventMulticaster.multicastEvent(orderEmployHasPayEvent);

                            OrderFinishEvent finishEvent = new OrderFinishEvent(rVo);
                            applicationEventMulticaster.multicastEvent(finishEvent);

                            if (null != passenger) {
                                ReactorVo rVo2 = new ReactorVo();
                                rVo2.setOrderChannelName(order.getOrderType());
                                rVo2.setOrderType(OrderType.daijia);
                                rVo2.setPassenger(passenger);
                                rVo2.setActivityEvent(ActivityEvent.orderCompleteTimes);
                                ActivityCheckEvent activityCheckEvent = new ActivityCheckEvent(
                                    rVo2);
                                applicationEventMulticaster.multicastEvent(activityCheckEvent);

                                MemberRebateEvent memberRebateEvent = new MemberRebateEvent(
                                    passenger, order,
                                    order.getRealCash(), 1);
                                applicationEventMulticaster.multicastEvent(memberRebateEvent);
                            }

                            ResultTransport instance = ResultTransport
                                .getErrorBy(ErrorConstantV4.SUCCESS);
                            instance.setData("hasfinished");
                            return instance;
                        } else {
                            ResultTransport instance = ResultTransport
                                .getErrorBy(ErrorConstantV4.SERVER_ERROR);
                            return instance;
                        }
                    } else {
                        order.setRealCash(realCash);
                    }
                    // 确认并报单
                    orderService.reportV3(order, null);
                    zWYApi.syncOrderInfo(order.getOrderNoRenBao(), order.getCuponNoRenBao(),
                        order.getOrderNumber(),
                        String.valueOf(5), order.getClientPhone());
                }
                // 客户端提醒付费推送
                OrderConfirmEvent orderConfirmEvent = new OrderConfirmEvent(order);
                applicationEventMulticaster.multicastEvent(orderConfirmEvent);
                ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
                instance.setData("waitfinish");
                return instance;
            }
        } catch (Exception e) {
            e.printStackTrace();
            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
            return instance;
        }
    }

    @RequestMapping(value = "finishTask", method = RequestMethod.POST)
    public @ResponseBody
    ResultTransport finishTask(Long orderId, String payType, String who) {

        logger.info("recv orderId:{},payType{}", orderId, payType);

        if (null == orderId || StringUtils.isBlank(payType)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        if (!"helppay".equals(payType) && !"sign".equals(payType) && !"balance".equals(payType)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.PARAM_ERROR);
        }

        Order order = orderService.findOne(orderId);

        if (null == order) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_EXISTS_ERROR);
        }

        if (order.getStatus().equals(Order.ORDER_STATUS_FINISHED)
            || order.getStatus().equals(Order.ORDER_STATUS_BAODAN)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_HAS_BEEN_FINISHED);
        }

        if (!order.getStatus().equals(Order.ORDER_STATUS_BUSY)) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_STATUS_ERROR);
        }

        if (!order.isTreatment()) {
            return ResultTransport.getErrorBy(ErrorConstantV4.ORDER_NOT_CONFIRM);
        }

        Setting setting = settingUtils.get();

        BigDecimal afterPayMoney = BigDecimal.ZERO;
        if (null != order.getPrePayTypeDetail()) {
            if (order.getPrePayTypeDetail().equals(PayTypeDetails.coupon)) {
                afterPayMoney = order.getRealCash().subtract(order.getCouponMoney());
            } else {
                afterPayMoney = order.getRealCash().subtract(order.getShouldCash());
            }
        } else {
            afterPayMoney = order.getRealCash();
        }

        Driver driver = driverService.findOne(order.getDriverId());
        if ("helppay".equals(payType)) {// 如果是代付，服务人员收到现金，余额减钱
            if (afterPayMoney.doubleValue() >= 10000) {
                return ResultTransport.getErrorBy(ErrorConstantV4.HELP_PAY_MONEY_TOOLARGE);
            }
            if (null == driver) {
                return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_NOT_EXISTS);
            }
            if (!setting.isAllowHelppayNe()) {
                if (driver.getVirtual().doubleValue() < (afterPayMoney.doubleValue())) {
                    return ResultTransport.getErrorBy(ErrorConstantV4.EMPLOY_MONEY_NOT_ENOUGH);
                }
            }
        }

        Passenger passenger = memberService.findOnePassenger(order.getClientId());
        if (null != passenger) {
            if ("sign".equals(payType)) {// 签单支付
                if (passenger.getType() == Passenger.TYPE_PASSENGER) {
                    if (!passenger.isAllowOverdraw()) {
                        return ResultTransport.getErrorBy(ErrorConstantV4.PASSENGER_NOT_ALLOW_SIGN);
                    }
                } else if (passenger.getType() == Passenger.TYPE_ENTERPRISE) {
                    Enterprise enterprise = memberService
                        .findOneEnterprise(passenger.getEnterprise_id());
                    if (!enterprise.isAllowOverdraw()) {
                        return ResultTransport.getErrorBy(ErrorConstantV4.PASSENGER_NOT_ALLOW_SIGN);
                    }
                }
            } else if ("balance".equals(payType)) {// 余额支付
                if (passenger.getType().equals(Passenger.TYPE_PASSENGER)) {
                    BigDecimal shengyuMoney = BigDecimal.ZERO;
                    shengyuMoney = shengyuMoney.add(passenger.getNodrawMoney());
                    if (passenger.getDrawMoney().doubleValue() > 0) {
                        shengyuMoney = shengyuMoney.add(passenger.getDrawMoney());
                    }
                    if (shengyuMoney.doubleValue() < (afterPayMoney.doubleValue())) {
                        return ResultTransport
                            .getErrorBy(ErrorConstantV4.PASSENGER_MONEY_NOT_ENOUGH);
                    }
                } else if (passenger.getType().equals(Passenger.TYPE_ENTERPRISE)) {
                    Enterprise enterprise = memberService
                        .findOneEnterprise(passenger.getEnterprise_id());
                    BigDecimal shengyuMoney = BigDecimal.ZERO;
                    shengyuMoney = shengyuMoney.add(enterprise.getNodrawMoney());
                    if (enterprise.getDrawMoney().doubleValue() > 0) {
                        shengyuMoney = shengyuMoney.add(enterprise.getDrawMoney());
                    }
                    if (shengyuMoney.doubleValue() < (afterPayMoney.doubleValue())) {
                        return ResultTransport
                            .getErrorBy(ErrorConstantV4.PASSENGER_MONEY_NOT_ENOUGH);
                    }
                }

            }
        }

        try {

            Result<Order> result = orderService
                .completeTaskNewV3(order, passenger, driver, "clickPay", payType, null,
                    false);

            if (result.isSuccess()) {

                // 完成工单事件
                ReactorVo rVo = new ReactorVo();
                rVo.setDriver(driver);
                rVo.setOrder(order);

                if (StringUtils.isNotBlank(who) && who.equals("passenger")) {
                    OrderPassengerHasPayEvent orderPassengerHasPayEvent = new OrderPassengerHasPayEvent(
                        driver,
                        order.getId(), "daijia");
                    applicationEventMulticaster.multicastEvent(orderPassengerHasPayEvent);
                } else {
                    OrderEmployHasPayEvent orderEmployHasPayEvent = new OrderEmployHasPayEvent(
                        passenger, order.getId(),
                        "daijia");
                    applicationEventMulticaster.multicastEvent(orderEmployHasPayEvent);
                }

                OrderFinishEvent finishEvent = new OrderFinishEvent(rVo);
                applicationEventMulticaster.multicastEvent(finishEvent);

                if (null != passenger) {
                    ReactorVo rVo2 = new ReactorVo();
                    rVo2.setOrderChannelName(order.getOrderType());
                    rVo2.setOrderType(OrderType.daijia);
                    rVo2.setPassenger(passenger);
                    rVo2.setActivityEvent(ActivityEvent.orderCompleteTimes);
                    ActivityCheckEvent activityCheckEvent = new ActivityCheckEvent(rVo2);
                    applicationEventMulticaster.multicastEvent(activityCheckEvent);

                    MemberRebateEvent memberRebateEvent = new MemberRebateEvent(passenger, order,
                        order.getRealCash(),
                        1);
                    applicationEventMulticaster.multicastEvent(memberRebateEvent);
                }

                ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SUCCESS);
                return instance;
            } else {
                if (result.getErrorcode()
                    .equals(String.valueOf(ErrorConstantV4.ORDER_HAS_BEEN_FINISHED.getCode()))) {
                    ResultTransport instance = ResultTransport
                        .getErrorBy(ErrorConstantV4.ORDER_HAS_BEEN_FINISHED);
                    return instance;
                } else {
                    ResultTransport instance = ResultTransport
                        .getErrorBy(ErrorConstantV4.SERVER_ERROR);
                    return instance;
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
            ResultTransport instance = ResultTransport.getErrorBy(ErrorConstantV4.SERVER_ERROR);
            return instance;
        }

    }

}
